package fm.shop.controller;

import fm.cache.ConfigCache;
import fm.controller.BaseController;
import fm.shop.service.SearchService;
import fm.web.MediaTypes;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @修改人：CM
 * @修改时间：2017/3/2 20:49
 */
@Controller
@RequestMapping("/search")
public class SearchController extends BaseController {
    @Autowired
    private SearchService searchService;

    @ResponseBody
    @RequestMapping(value = "", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map searchData(ModelMap modelMap,
                          @RequestParam(value = "t", required = false) String type,
                          @RequestParam(value = "k", required = true) String keywords,
                          @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                          @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.put("uuid", getCurrentPublicNumber().getUuid());
            List<String> tables = new ArrayList<>();

            if (StringUtils.isNotEmpty(type)) {
                tables.add(type);
            } else {
                tables = Arrays.asList(StringUtils.split(ConfigCache.getConfig("SEARCHABLE_RESOURCE_TABLE"), ","));
            }

            ConcurrentHashMap<String, Collection> datas = searchService.searchByKeyword(URLDecoder.decode(keywords, "UTF-8"), tables);
            response.put("data", datas);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;

    }
}
